package mygang.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
public class UserWrapper extends org.springframework.security.core.userdetails.User {
    
    private User wrappedUser = null;
    private String name;

    public UserWrapper(User user) {
        super(user.getLogin(), user.getPassword(), user.isActive(), true, true, user.isActive(), getGrantedAuthorities(user));
        wrappedUser = user;
        this.name = user.getLogin();
    }
    
    public long getId(){
        return wrappedUser.getId();
    }
    
    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    
    @Override
    public Collection<GrantedAuthority> getAuthorities(){
        return getGrantedAuthorities(wrappedUser);
    }
    
    private static Collection<GrantedAuthority> getGrantedAuthorities(User user) {
        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        Set<Role> roles = user.getRoles();
        if(roles != null) {
            for(Role role : roles){
                authorities.add(new SimpleGrantedAuthority(role.getName()));
            }
        }
        return authorities;
    }
}
